package com.jiangyg.devtools.toolkit;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * ģ幤
 *
 * @author jiangyg
 * @date 2023-08-13
 */
public class TemplateUtils {

    private static final Configuration CFTLCFG = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    private static final Configuration SFTLCFG = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    static {
        //cfg.setDirectoryForTemplateLoading(new File(path));
        CFTLCFG.setClassForTemplateLoading(TemplateUtils.class, "/ftl");
        CFTLCFG.setDefaultEncoding("utf-8");
        CFTLCFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        SFTLCFG.setTemplateLoader(new StringTemplateLoader());
        SFTLCFG.setDefaultEncoding("utf-8");
        SFTLCFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    }

    /**
     * 功能描述：控制台打印模板输出
     *
     * @param name 模板文件名
     * @param data 数据
     * @return 模板结果
     * @throws Exception 异常
     */
    public static String template(String name, Object data) throws Exception {
        final StringWriter writer = new StringWriter();

        Template template = CFTLCFG.getTemplate(name);
        template.process(data, writer);

        return writer.toString();
    }

    /**
     * 功能描述：控制台打印模板输出
     *
     * @param name 模板文件名
     * @param data 数据
     * @throws Exception 异常
     */
    public static void print(String name, Object data) throws Exception {
        PrintWriter writer = new PrintWriter(System.out);
        Template template = CFTLCFG.getTemplate(name);
        template.process(data, writer);
    }

    /**
     * 功能描述：根据字符串模板输出结果
     *
     * @param name           模板名称
     * @param templateString 模板内容
     * @param data           数据
     * @return 结果
     * @throws Exception 异常
     */
    public static String template(String name, String templateString, Object data) throws Exception {
        final StringWriter writer = new StringWriter();
        final Template template = new Template(name, templateString, SFTLCFG);
        template.process(data, writer);
        return writer.toString();
    }

}
